package com.chenyue.cm.api.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.auth.token.LoginUserInfo;
import com.chenyue.cm.auth.token.RequestUtil;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.live.domain.JdLive;
import com.chenyue.cm.live.service.JdLiveRecordService;
import com.chenyue.cm.live.service.JdLiveService;
import com.chenyue.cm.live.vo.LiveUser;
import com.chenyue.cm.live.vo.SetLiveUser;
import com.chenyue.cm.live.vo.param.SetMatchLiveUser;
import com.chenyue.cm.match.domain.*;
import com.chenyue.cm.match.service.*;
import com.chenyue.cm.match.vo.MatchSignUserInfo;
import com.chenyue.cm.match.vo.ThirdCreateMatch;
import com.chenyue.cm.match.vo.param.ThirdSetLiveRoom;
import com.chenyue.cm.msg.service.PushService;
import com.chenyue.cm.news.domain.JdNews;
import com.chenyue.cm.news.service.JdNewsService;
import com.chenyue.cm.news.vo.NewInfoVo;
import com.chenyue.cm.user.domain.*;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.service.JdLabelSendService;
import com.chenyue.cm.user.service.JdThirdApplyService;
import com.chenyue.cm.user.service.JdVerifyService;
import com.chenyue.cm.user.vo.CheckMobileUserVo;
import com.chenyue.cm.utils.DateUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: ljy
 * @Title: ApiThirdController
 * @Description: 第三方机构api
 * @Date: 2021-08-04
 */
@RestController
@RequestMapping("/api/third")
@Api(value = "第三方机构api", tags = "第三方机构api")
@ApiSort(7)
public class ApiThirdController {

    private final JdThirdApplyService thirdApplyService;

    private final JdLabelSendService labelSendService;

    private final JdVerifyService verifyService;

    private final JdNewsService newsService;

    private final JdMatchService matchService;

    private final JdMatchSignService matchSignService;

    private final ViewMatchItemService viewMatchItemService;

    private final JdLiveService liveService;

    private final JdLiveRecordService recordService;

    private final JdAppUserService appUserService;

    private final JdMatchWhiteApplyService whiteApplyService;

    private final FormatLiveUserService formatLiveUserService;

    private final FormatLiveRecordService formatLiveRecordService;

    private final JdMatchFormatMemberService matchFormatMemberService;

    private final JdMatchFormatService matchFormatService;

    private final PushService pushService;

    public ApiThirdController(
            JdThirdApplyService thirdApplyService,
            JdLabelSendService labelSendService, JdVerifyService verifyService,
            JdNewsService newsService,
            JdMatchService matchService,
            JdMatchSignService matchSignService, ViewMatchItemService viewMatchItemService, JdLiveService liveService,
            JdLiveRecordService recordService, JdAppUserService appUserService,
            JdMatchWhiteApplyService whiteApplyService, FormatLiveUserService formatLiveUserService, FormatLiveRecordService formatLiveRecordService, JdMatchFormatMemberService matchFormatMemberService, JdMatchFormatService matchFormatService, PushService pushService) {
        this.thirdApplyService = thirdApplyService;
        this.labelSendService = labelSendService;
        this.verifyService = verifyService;
        this.newsService = newsService;
        this.matchService = matchService;
        this.matchSignService = matchSignService;
        this.viewMatchItemService = viewMatchItemService;
        this.liveService = liveService;
        this.recordService = recordService;
        this.appUserService = appUserService;
        this.whiteApplyService = whiteApplyService;
        this.formatLiveUserService = formatLiveUserService;
        this.formatLiveRecordService = formatLiveRecordService;
        this.matchFormatMemberService = matchFormatMemberService;
        this.matchFormatService = matchFormatService;
        this.pushService = pushService;
    }

    @Login
    @PostMapping("/thirdApply")
    @ApiOperation(value = "第三方机构入驻", notes = "第三方机构入驻")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机", name = "mobile", dataType = "String", required = true),
            @ApiImplicitParam(value = "验证码", name = "verifyCode", dataType = "String", required = true),
    })
    public Success<String> thirdApply(
            @ApiParam @RequestBody JdVerify info,
            String mobile, String verifyCode,
            @ApiIgnore @LoginUser JdAppUser user
    ) {
        String errorMsg = appUserService.checkVerifyCode(mobile, verifyCode);
        //        校验验证码
        if (StringUtils.isNotBlank(errorMsg)) {
            return Success.error(errorMsg);
        }
        int type = 1;
        if (StringUtils.isNotBlank(info.getBusPositive())) {
//            企业
            type = 2;
        }
        info.setUserId(Integer.valueOf(user.getId()));
        verifyService.saveVerify(info);
        return thirdApplyService.thirdApply(info.getUserId(), type);
    }

    @Login
    @GetMapping("/applyState")
    @ApiOperation("查看三方机构入驻申请状态")
    public Success<JdThirdApply> applyState(
            @ApiIgnore @LoginUser JdAppUser user
    ) {
        final JdThirdApply one = thirdApplyService.lambdaQuery()
                .eq(JdThirdApply::getUserId, user.getId())
                .orderByAsc(JdThirdApply::getCheckState)
                .orderByDesc(JdThirdApply::getCt)
                .last(" limit 1 ")
                .one();
        return Success.success(one);
    }

    @PostMapping("/getThirdInfo")
    @ApiOperation(value = "第三方机构详情", notes = "第三方机构详情")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id（不传就是当前登录用户）", name = "matchId", dataType = "int"),
    })
    public Success<JdThirdInformation> getThirdInfo(
            HttpServletRequest request, Integer matchId
    ) {
        Integer userId = 0;
        final LoginUserInfo userInfo;
        try {
            userInfo = RequestUtil.getUserInfoByRequest(request);
            userId = userInfo.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != matchId) {
            userId = matchService.getById(matchId).getCu();
        }
        JdThirdInformation thirdInformation = thirdApplyService.thirdInformation(userId);
        return Success.success(thirdInformation);
    }

    @Login
    @PostMapping("/editThirdInfo")
    @ApiOperation("第三方机构详情编辑")
    public Success<JdThirdInformation> editThirdInfo(
            @ApiParam JdThirdInformation information
    ) {
        thirdApplyService.editThirdInfo(information);
        return Success.success();
    }

    @PostMapping("/getRelatedNews")
    @ApiOperation(value = "第三方机构详情中相关新闻", notes = "第三方机构详情中相关新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
            @ApiImplicitParam(value = "赛事id（不传就是当前登录用户）", name = "matchId", dataType = "int"),
    })
    public Success<Page<List<NewInfoVo>>> getRelatedNews(
            HttpServletRequest request, Integer matchId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows
    ) {
        Integer userId = 0;
        final LoginUserInfo userInfo;
        try {
            userInfo = RequestUtil.getUserInfoByRequest(request);
            userId = userInfo.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != matchId) {
            userId = matchService.getById(matchId).getCu();
        }
        final Integer total = newsService.lambdaQuery().eq(JdNews::getCu, userId).count();
        final Page<List<NewInfoVo>> result = new Page<>(page, rows, total);
        List<NewInfoVo> relatedNewsList = newsService.getNewsListByUser(userId);
        result.setContent(relatedNewsList);
        return Success.success(result);
    }

    @PostMapping("/getMatchByThird")
    @ApiOperation(value = "第三方机构发布的赛事列表（带分页）", notes = "第三方机构发布的赛事列表（带分页）")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
            @ApiImplicitParam(value = "审核状态 0全部 1待审核 2通过 3拒绝", name = "state", dataType = "int", required = true),
            @ApiImplicitParam(value = "赛事id（不传就是当前登录用户）", name = "matchId", dataType = "int"),
            @ApiImplicitParam(value = "晋级方式0自动1手动", name = "promotionType", dataType = "int"),
    })
    public Success<Page<List<MatchInfo>>> getMatchByThird(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            Integer state, Integer promotionType,
            Integer matchId, HttpServletRequest request
    ) {
        Integer userId;
        if (null != matchId) {
            userId = matchService.getById(matchId).getCu();
        } else {
            final LoginUserInfo userInfo;
            try {
                userInfo = RequestUtil.getUserInfoByRequest(request);
                userId = userInfo.getUserId();
            } catch (Exception ignore) {
                userId = 0;
            }
        }
        Page<List<MatchInfo>> match = matchService.getMatchByUser(page, rows, state, userId, promotionType);
        return Success.success(match);
    }

    @Login
    @PostMapping("/getLiveUserList")
    @ApiOperation(value = "第三方机构下的主播列表（带分页）", notes = "第三方机构下的主播列表（带分页）")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
    })
    public Success<Page<List<LiveUser>>> getLiveUserList(
            @ApiIgnore @LoginUser JdAppUser user, Integer page, Integer rows
    ) {
        Page<List<LiveUser>> liveUserList = liveService.getLiveUserList(String.valueOf(user.getId()), page, rows, null);
        return Success.success(liveUserList);
    }

    @Login
    @PostMapping("/setLiveUser")
    @ApiOperation(value = "第三方机构 设置赛事主播", notes = "第三方机构 设置赛事主播")
    @ApiOperationSupport(order = 6)
    public Success<String> setLiveUser(
            @ApiIgnore @LoginUser JdAppUser user,
            @ApiParam @RequestBody List<SetLiveUser> liveUserList
    ) {
        return liveService.setLiveUser(liveUserList, Integer.valueOf(user.getId()));
    }

    @Login
    @PostMapping("/getLiveRoom")
    @ApiOperation("获取直播间")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛程id", name = "formatId", dataType = "int", required = true),
    })
    public Success<ThirdSetLiveRoom> setLiveRoom(
            Integer formatId
    ) {
        return Success.success(matchService.getLiveRoom(formatId));
    }

    @Login
    @PostMapping("/setLiveRoom")
    @ApiOperation("分配直播间")
    public Success<String> setLiveRoom(
            @ApiParam @RequestBody ThirdSetLiveRoom setLiveRoom
    ) {
        if (setLiveRoom.getLiveUserList() == null) {
            return Success.error("分配数据异常");
        }
        matchService.setLiveRoom(setLiveRoom.getMatchId(), setLiveRoom.getLiveUserList(), setLiveRoom.getFormatId());
        return Success.success();
    }

    @Login
    @PostMapping("/formatMemberList")
    @ApiOperation("可分配参赛员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛程阶段", name = "arrangeOrder", dataType = "string", required = true),
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "string", required = true),
    })
    public Success<List<FormatLiveUser>> formatMemberList(
            Integer arrangeOrder, Integer matchId
    ) {
        final List<FormatLiveUser> list = formatLiveUserService.lambdaQuery()
                .eq(FormatLiveUser::getArrangeOrder, arrangeOrder)
                .eq(FormatLiveUser::getMatchId, matchId).list();
        return Success.success(list);
    }

    @Login
    @PostMapping("/formatMemberListGroup")
    @ApiOperation("可分配参赛员列表-团队")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛程阶段", name = "arrangeOrder", dataType = "string", required = true),
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "string", required = true),
    })
    public Success<List<FormatLiveUser>> formatMemberListGroup(
            Integer arrangeOrder, Integer matchId
    ) {
        List<FormatLiveUser> list = formatLiveUserService.lambdaQuery()
                .eq(FormatLiveUser::getArrangeOrder, arrangeOrder)
                .eq(FormatLiveUser::getMatchId, matchId).groupBy(FormatLiveUser::getGroupId).list();
        for (FormatLiveUser formatLiveUser : list) {
            List<FormatLiveUser> child = formatLiveUserService.lambdaQuery()
                    .eq(FormatLiveUser::getArrangeOrder, arrangeOrder)
                    .eq(FormatLiveUser::getMatchId, matchId)
                    .eq(FormatLiveUser::getGroupId, formatLiveUser.getGroupId())
                    .list();
            formatLiveUser.setList(child);
        }
        return Success.success(list);
    }

    @Login
    @PostMapping("/formatLiveRecord")
    @ApiOperation("赛程直播间列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛程阶段", name = "arrangeOrder", dataType = "string", required = true),
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "string", required = true),
    })
    public Success<List<FormatLiveRecord>> formatLiveList(
            Integer arrangeOrder, Integer matchId
    ) {
        final List<FormatLiveRecord> list = formatLiveRecordService.lambdaQuery()
                .eq(FormatLiveRecord::getArrangeOrder, arrangeOrder)
                .eq(FormatLiveRecord::getMatchId, matchId).list();
        return Success.success(list);
    }

    @PostMapping("/isSetMatchLiveUser")
    @ApiOperation("分配参赛员 - 检测是否已分配")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id/团队id", name = "id", dataType = "integer", required = true),
            @ApiImplicitParam(value = "1个人2团队", name = "type", dataType = "integer", required = true),
            @ApiImplicitParam(value = "赛程id", name = "formatArrangeId", dataType = "integer", required = true),
    })
    public Success<String> isSetMatchLiveUser(
            Integer id, Integer type, Integer formatArrangeId
    ) {
        recordService.isSetMatchLiveUser(id, type, formatArrangeId);
        return Success.success();
    }

    @Login
    @PostMapping("/setMatchLiveUser")
    @ApiOperation("分配参赛员")
    public Success<String> setMatchLiveUser(
            @ApiParam @RequestBody SetMatchLiveUser matchLiveUser
    ) {
        recordService.setMatchLiveUser(matchLiveUser);
        return Success.success();
    }

    @Login
    @PostMapping("/setLiveUserCheck")
    @ApiOperation(value = "第三方机构 设置赛事主播前 每个手机号需要单独校验", notes = "第三方机构 设置赛事主播每个手机号需要单独校验")
    @ApiOperationSupport(order = 6)
    public Success<String> setLiveUserCheck(
            @ApiParam @RequestBody SetLiveUser liveUserList
    ) {
        JdAppUser appUser;
        if (11 != liveUserList.getNumber().length()) {
            appUser = appUserService.getOne(new QueryWrapper<JdAppUser>().lambda()
                    .eq(JdAppUser::getUserNum, liveUserList.getNumber())
                    .last(" limit 1")
            );
            if (null == appUser) {
                return Success.error("无此ID");
            }
        } else {
            List<CheckMobileUserVo> voList = new ArrayList<>();
            CheckMobileUserVo vo = new CheckMobileUserVo();
            vo.setMobile(liveUserList.getNumber());
            voList.add(vo);
            //校验手机号，没有就注册
            appUserService.checkMobileUser(voList);
            appUser = appUserService.getOne(new QueryWrapper<JdAppUser>().lambda()
                    .eq(JdAppUser::getMobile, liveUserList.getNumber())
                    .last(" limit 1")
            );
        }
        JdLive live = liveService.lambdaQuery().eq(JdLive::getUserId, appUser.getId()).last(" limit 1").one();
        if (live != null) {
            return Success.error("用户" + liveUserList.getNumber() + "已经是主播");
        }
        return Success.success();
    }

    @Login
    @PostMapping("/deleteLiveUser")
    @ApiOperation(value = "第三方机构 删除赛事主播", notes = "第三方机构 删除赛事主播")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主播id", name = "liveId", dataType = "int", required = true),
    })
    public Success<String> deleteLive(Integer liveId) {
        liveService.deleteLive(liveId);
        return liveService.removeById(liveId) ? Success.success() : Success.error();
    }

    @Login
    @PostMapping("/getSignUserList")
    @ApiOperation(value = "第三方机构 报名赛事的用户列表", notes = "第三方机构 报名赛事的用户列表")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "int", required = true),
            @ApiImplicitParam(value = "审核状态1审核通过", name = "checkState", dataType = "int", required = true),
            @ApiImplicitParam(value = "支付状态1已支付", name = "payState", dataType = "int", required = true),
    })
    public Success<List<MatchSignUserInfo>> getSignUserList(
            Integer matchId, @ApiIgnore @LoginUser JdAppUser user,
            Integer checkState, Integer payState
    ) {
        List<MatchSignUserInfo> signUserInfos = matchService.signUserList(matchId, checkState, payState);
        for (MatchSignUserInfo signUserInfo : signUserInfos) {
            final List<JdLabelSend> list = labelSendService.lambdaQuery()
                    .eq(JdLabelSend::getReferUser, user.getId())
                    .eq(JdLabelSend::getGetUser, signUserInfo.getUserId())
                    .list();
            signUserInfo.setLabelList(list);
        }
        return Success.success(signUserInfos);
    }

    @Login
    @PostMapping("/signCheck")
    @ApiOperation(value = "第三方机构 审核赛事报名", notes = "第三方机构 审核赛事报名")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "报名id", name = "signId", dataType = "int", required = true),
            @ApiImplicitParam(value = "审核状态 1通过2拒绝", name = "state", dataType = "int", required = true),
    })
    public Success<String> signCheck(Integer signId, Integer state) {
        matchService.signCheck(signId, state);
        return Success.success();
    }

    @Login
    @PostMapping("/thirdCreateMatch")
    @ApiOperation(value = "第三方机构 发布赛事（传实体类）", notes = "第三方机构 发布赛事（传实体类）")
    @ApiOperationSupport(order = 10)
    public Success<String> createMatch(
            @ApiIgnore @LoginUser JdAppUser user,
            @ApiParam @RequestBody ThirdCreateMatch matchInfo
    ) {
        matchService.thirdCreateMatch(matchInfo, Integer.valueOf(user.getId()));
        return Success.success();
    }

    @Login
    @PostMapping("/thirdGetMatch")
    @ApiOperation("赛事编辑回显")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "int", required = true),
    })
    public Success<ThirdCreateMatch> thirdGetMatch(
            Integer matchId
    ) {
        final ThirdCreateMatch result = new ThirdCreateMatch();
        final JdMatch match = matchService.getById(matchId);
        BeanUtils.copyProperties(match, result);
        final ViewMatchItem one = viewMatchItemService.lambdaQuery().eq(ViewMatchItem::getId, matchId).one();
        result.setMatchItemNames(one.getItemNames());
        result.setMatchItems(one.getItemIds());
        result.setMatchArea(match.getAddress());
        result.setTypeName(one.getTypeName());
        final List<JdMatchFormat> list = matchFormatService.lambdaQuery().eq(JdMatchFormat::getMatchId, matchId).list();
        List<ThirdCreateMatch.MatchFormat> formats = new ArrayList<>(list.size());
        for (JdMatchFormat format : list) {
            ThirdCreateMatch.MatchFormat matchFormat = new ThirdCreateMatch.MatchFormat();
            BeanUtils.copyProperties(format, matchFormat);
            matchFormat.setLiveList(formatLiveRecordService.lambdaQuery().eq(FormatLiveRecord::getArrangeId, format.getId()).list());
            formats.add(matchFormat);
        }
        result.setFormats(formats);
        return Success.success(result);
    }

    @Login
    @PostMapping("/labelSend")
    @ApiOperation("指定标签-团队/个人")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "标签内容", name = "labelContent", dataType = "string", required = true),
            @ApiImplicitParam(value = "被指定-用户id", name = "userId", dataType = "integer"),
            @ApiImplicitParam(value = "被指定-团队id", name = "groupId", dataType = "integer")
    })
    public Success<JdLabelSend> labelSend(
            @ApiIgnore @LoginUser JdAppUser user,
            String labelContent, Integer userId, Integer groupId
    ) {
        JdLabelSend label = new JdLabelSend();
        label.setGetGroup(groupId);
        label.setGetUser(userId);
        label.setReferUser(Integer.valueOf(user.getId()));
        label.setLabel(labelContent);
        final boolean save = labelSendService.save(label);
        return save ? Success.success(label) : Success.error();
    }

    @Login
    @PostMapping("/labelCancel")
    @ApiOperation("删除标签-团队/个人")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "标签id", name = "id", dataType = "integer", required = true)
    })
    public Success<String> labelCancel(
            Integer id
    ) {
        labelSendService.delete(id);
        return Success.success();
    }

    @Login
    @GetMapping("/whiteList")
    @ApiOperation("白名单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页数", name = "page", dataType = "string", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "string", required = true),
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "string", required = true),
    })
    public Success<Page<List<JdAppUser>>> whiteList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            @LoginUser @ApiIgnore JdAppUser user,
            Integer matchId
    ) {
        final LambdaQueryChainWrapper<JdMatchWhiteApply> eq = whiteApplyService.lambdaQuery()
                .eq(JdMatchWhiteApply::getCu, user.getId())
                .eq(JdMatchWhiteApply::getMatchId, matchId);
        final Integer total = eq
                .count();
        final Page<List<JdAppUser>> result = new Page<>(page, rows, total);
        final List<JdMatchWhiteApply> list = eq.last(result.convertPage()).list();
        if (list != null && list.size() > 0) {
            final List<JdAppUser> userList = appUserService.lambdaQuery().in(JdAppUser::getId, list.stream().map(JdMatchWhiteApply::getUserId).collect(Collectors.toList())).list();
            result.setContent(userList);
        } else {
            result.setContent(new ArrayList<>());
        }
        return Success.success(result);
    }

    @Login
    @GetMapping("/whiteApply")
    @ApiOperation("白名单管理")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "string", required = true),
            @ApiImplicitParam(value = "用户id/手机号 ,分割", name = "ids", dataType = "string", required = true),
    })
    @Transactional(rollbackFor = Exception.class)
    public Success<Page<List<JdMatchWhiteApply>>> whiteApply(
            Integer matchId, String ids,
            @LoginUser @ApiIgnore JdAppUser appUser
    ) {
        for (String s : ids.split(",")) {
            final JdAppUser user = liveService.getUserByIdOrPhone(s);
            if (user == null) {
                return Success.error("用户 " + s + " 不存在！");
            }
            final JdMatchWhiteApply one = whiteApplyService.lambdaQuery()
                    .eq(JdMatchWhiteApply::getMatchId, matchId)
                    .eq(JdMatchWhiteApply::getUserId, user.getId()).one();
            if (one == null) {
                final JdMatchSign sign = matchSignService.lambdaQuery().eq(JdMatchSign::getMatchId, matchId).eq(JdMatchSign::getUserId, user.getId()).last(" limit 1").one();
                if (sign != null) {
                    return Success.error("用户 " + s + " 已经报名！");
                }
                final JdMatchFormat format = matchFormatService.lambdaQuery().eq(JdMatchFormat::getMatchId, matchId).eq(JdMatchFormat::getArrangeOrder, 3).one();
                final JdMatchFormatMember oldSign = matchFormatMemberService.lambdaQuery()
                        .eq(JdMatchFormatMember::getFormatId, format.getId())
                        .eq(JdMatchFormatMember::getUserId, user.getId())
                        .one();
                if (oldSign != null) {
                    return Success.error("用户 " + s + " 已经加入了决赛！");
                }
//                白名单记录
                JdMatchWhiteApply white = new JdMatchWhiteApply();
                white.setMatchId(matchId);
                white.setUserId(Integer.valueOf(user.getId()));
                white.setCu(appUser.getId() + "");
                white.setCt(Calendar.getInstance().getTime());
                boolean flag = whiteApplyService.save(white);
                if (!flag) {
                    throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
                }
//                白名单推送
                pushService.whiteApplyPush(white);
//                赛程人员记录
                JdMatchFormatMember formatMember = new JdMatchFormatMember();
                formatMember.setUserId(Integer.valueOf(user.getId()));
                formatMember.setFormatId(format.getId());
                formatMember.setGroupId(0);
                flag = matchFormatMemberService.save(formatMember);
                if (!flag) {
                    throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
                }
//                报名记录
                JdMatchSign matchSign = new JdMatchSign();
                matchSign.setMatchId(matchId);
                matchSign.setCt(DateUtils.getToday());
                matchSign.setState(1);
                matchSign.setPayState(1);
                matchSign.setGroupId(0);
                matchSign.setUserId(Integer.valueOf(user.getId()));
                matchSign.setRemark("白名单用户");
                flag = matchSignService.save(matchSign);




                if (!flag) {
                    throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
                }
            } else {
                return Success.error("用户 " + s + " 已经加入了白名单！");
            }
        }
        return Success.success();
    }

}
